<template>
  <div class="app-container">
    <el-form label-width="120px">
      <h2 style="text-align: center;">发布新课程</h2>
      <el-steps
        :active="1"
        process-status="wait"
        align-center
        style="marginbottom: 40px;"
      >
        <el-step title="填写课程基本信息" />
        <el-step title="创建课程大纲" />
        <el-step title="最终发布" />
      </el-steps>
    </el-form>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input
          v-model="courseInfo.title"
          placeholder=" 示例：机器学习项目课：从基础到搭建项目"
        />
      </el-form-item>

      <!-- 所属分类：级联下拉列表 提交value-->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="一级分类"
          @change="getSubjetInfo"
        >
          <el-option
            v-for="subjectOne in subjectOneList"
            :key="subjectOne.id"
            :label="subjectOne.title"
            :value="subjectOne.id"
          />
        </el-select>

        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
          <el-option
            v-for="subjectTwo in subjectTwoList"
            :key="subjectTwo.id"
            :label="subjectTwo.title"
            :value="subjectTwo.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程讲师 TODO -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时"
        />
      </el-form-item>
      <!-- 课程简介 TODO -->
      <!-- <el-form-item label="课程简介">
        <el-input v-model="courseInfo.description" placeholder="课程简介" />
      </el-form-item> -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <!-- 课程封面 TODO -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/eduoss/fileoss/uploadOssFile'"
          class="avatar-uploader"
        >
          <img :src="courseInfo.cover" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="请填写课程价格"
        />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">
          保存并下一步
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import course from "@/api/edu/course";
import subject from "@/api/edu/subject";
import Tinymce from "@/components/Tinymce";

const defaultForm = {
  title: "",
  subjectId: "", // 二级分类id
  subjectParentId: "", // 一级分类id
  teacherId: "",
  lessonNum: 0,
  description: "",
  cover: "/static/javaFengMian.jpg",
  price: 0
};
export default {
  components: { Tinymce },
  data() {
    return {
      BASE_API: process.env.BASE_API,
      courseInfo: defaultForm,
      saveBtnDisabled: false, // 保存按钮是否禁用
      teacherList: [],
      subjectOneList: [],
      subjectTwoList: [],
      courseId: '',
    };
  },
  created() {
    // 返回本页
    this.init()
  },
  watch: {
    $route(to, from) {
      console.log("watch $route");
      this.init();
    }
  },
  methods: {
    init() {
      if (this.$route.params && this.$route.params.id){
        this.courseId = this.$route.params.id
        // 根据id查询课程信息
        this.getCourseInfo()
      } else {
        this.courseInfo = defaultForm
      }
      this.getSubjectOne();
      this.getListTeacher();
    },
    getCourseInfo(){
      course.getCourseInfo(this.courseId).then(response => {
        this.courseInfo = response.data.courseInfoVo
        this.getSubjectOne()
        subject.getSubjectList().then(response => {
          // 获取以及分类
          this.subjectOneList = response.data.data
          // 遍历
          for (let i = 0; i < this.subjectOneList.length; i ++) {
            let oneSubject = this.subjectOneList[i]
            if (this.courseInfo.subjectParentId == oneSubject.id) {
              // 获取二级分类
              this.subjectTwoList = oneSubject.children
              break
            }
          }
        })
      })
    },
    // 上传成功方法
    handleAvatarSuccess(res, file) {
      console.log(res); // 上传响应
      console.log(URL.createObjectURL(file.raw)); // base64编码
      this.courseInfo.cover = res.data.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 获取二级分类 参数自动传入的
    getSubjetInfo(value) {
      for (let i = 0; i < this.subjectOneList.length; i++) {
        let subjectOne = this.subjectOneList[i];
        if (subjectOne.id === value) {
          this.subjectTwoList = subjectOne.children;
          break;
        }
      }
      this.courseInfo.subjectId = "";
    },
    // 查询所有一级分类
    getSubjectOne() {
      subject.getSubjectList().then(response => {
        this.subjectOneList = response.data.data;
      });
    },
    //查询所有讲师
    getListTeacher() {
      course.getListTeacher().then(response => {
        this.teacherList = response.data.item;
      });
    },
    next() {
      console.log("next");
      this.saveBtnDisabled = true;
      if (!this.courseInfo.id) {
        this.saveData();
      } else {
        this.updateData(this.courseInfo.id);
      }
    },
    saveData() {
      course.saveCourseInfo(this.courseInfo).then(response => {
        this.$message({
          type: "success",
          message: "保存成功!"
        });
        this.$router.push({
          path: "/course/chapter/" + response.data.courseId
        });
      });
    },
    updateData(courseId) {
      course.updateCourseInfo(this.courseInfo).then(response => {
        this.$message({
          type: "success",
          message: "保存成功!"
        })
      })
      this.$router.push({ path: "/course/chapter/" + courseId});
    }
  }
};
</script>
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
